"""
用来查询取消航班的信息
"""
import datetime
import re

from selenium import webdriver
from selenium.webdriver import ChromeOptions
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait


class AirLineCheck:

    def __init__(self):
        option = ChromeOptions()
        option.add_argument("--headless")
        option.add_argument("--disable-gpu")
        option.add_experimental_option('excludeSwitches', ['enable-automation'])
        option.add_experimental_option('useAutomationExtension', False)
        self.browser = webdriver.Chrome(options=option, executable_path=r'C:\chromedriver\chromedriver.exe')
        self.browser.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {
            'source': 'Object.defineProperty(navigator, "webdriver", {get: () => undefined})'
        })
        self.browser.implicitly_wait(10)

    def getAirLinesList(self, departCity, destination, departDate):
        """
        :param departCity: 出发城市代码，武汉为WUH
        :param destination: 目的城市代码，三亚为SYX
        :param departDate: 出发日期,格式是'2020-09-20'
        :return:航班号列表
        """
        result = []

        url = 'https://flights.ctrip.com/itinerary/oneway/{}-{}?date={}'.format(departCity, destination, departDate)

        self.browser.get(url)
        r = self.browser.page_source
        airLineList = re.findall(r'data-mark="(.+?)"', r)
        for i in airLineList:
            airLine = i.split('|')[0]
            result.append(airLine)
        return result

    def airLineFilter(self, airLine, departDate):
        """
        :param departDate: 起飞日期
        :param airLine: 航班号
        :return: 航班状态
        """
        self.browser.get('http://www.variflight.com')
        # 等待 首页 元素出现
        try:
            WebDriverWait(self.browser, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="numDatepicker"]')))
            # js去掉readonly属性
            js = 'document.getElementById("numDatepicker").removeAttribute("readonly");'
            self.browser.execute_script(js)
            # 使用js控制，输入日期
            js_value = "document.getElementById('numDatepicker').value='{}'".format(departDate)
            self.browser.execute_script(js_value)
            # 输入航班号
            inputBar = self.browser.find_element_by_xpath('//*[@id="byNumInput"]')
            inputBar.send_keys(airLine)
            # 按下搜索
            searchButton = self.browser.find_element_by_xpath('//*[@id="byNumBtn"]')
            searchButton.click()
            # 等待搜索结果出现
            WebDriverWait(self.browser, 10).until(EC.presence_of_element_located((By.CLASS_NAME, 'fly_list')))
            r = self.browser.find_element_by_xpath('//*[@id="list"]').text
            if '取消' in r or '延误' in r:
                return self.browser.title
            else:
                pass
        except:
            pass




if __name__ == '__main__':
    departCityCodes = ['bjs', 'wuh', 'sha', 'can', 'szx', 'ctu', 'hgh', 'sia', 'ckg', 'tao', 'csx', 'nkg', 'xmn', 'kmg',
                       'dlc', 'tsn', 'cgo', 'tna', 'foc']
    destinationCity = 'syx'
    departureDate = '2020-09-20'
    nextWeekDay = (datetime.datetime.strptime(departureDate, '%Y-%m-%d') + datetime.timedelta(days=7)).strftime(
        '%Y-%m-%d')

    s = AirLineCheck()
    airList = []
    for departCity in departCityCodes:
        airLine = s.getAirLinesList(departCity, destinationCity, nextWeekDay)
        airList.extend(airLine)

    for airLine in airList:
        result = s.airLineFilter(airLine, departureDate)
        if result:
            print(result)
